/**
 * Project: apollo-base-tools
 * 
 * File Created at 2017年8月7日
 * 
 * Copyright 2015-2016 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package org.apollo.sqlite.core;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.PooledConnection;

import org.apache.log4j.Logger;
import org.apollo.sqlite.utils.DBConfig;
import org.apollo.sys.SysLog;

/** 
* @ClassName: SQLiteConnectionPool 
* @Description: sqlite连接池工厂
* @author wuzhenfang(wzfbj2008@163.com)
* @date 2017年8月7日 下午8:07:14 
* @version V1.0 
*/
public class SQLiteConnectionFactory {

	private final static Logger Log = SysLog.getLogger(SQLiteConnectionFactory.class);

	private DBConfig config;

	private SQLiteDatabase database;

	private PooledConnection pooledConn;

	private ThreadLocal<Connection> threadLocalStat = new ThreadLocal<Connection>();

	private SQLiteConnectionFactory() {
	}

	private static class SingletonHolder {
		private static SQLiteConnectionFactory INSTANCE = new SQLiteConnectionFactory();

	}

	public static SQLiteConnectionFactory instance() {
		return SingletonHolder.INSTANCE;
	}

	public void init(String configPath) {
		config = new DBConfig(configPath);
		database = new SQLiteDatabase(config);
		try {
			pooledConn = database.getPooledConnection();
		} catch (SQLException e) {
			Log.error("初始化连接池出错。", e);
		}
	}

	/**
	 * 获得连接
	 * @return
	 * @throws SQLException
	 */
	public Connection getConnection() throws SQLException {
		Connection connection = this.pooledConn.getConnection();
		threadLocalStat.set(connection);
		return connection;
	}

	public Statement getStatement() throws SQLException {
		Statement statement = getConnection().createStatement();
		statement.setQueryTimeout(30);
		return statement;
	}

	public void close() {
		try {
			threadLocalStat.get().isClosed();
			threadLocalStat.remove();
		} catch (SQLException e) {
			Log.error("关闭连接失败出错。", e);
		}
	}

	/**
	 * @return the config
	 */
	public DBConfig getConfig() {
		return config;
	}

	/**
	 * @return the database
	 */
	public SQLiteDatabase getDatabase() {
		return database;
	}

}
